import 'package:flutter/material.dart';

class BaseCustomSwitchButton extends StatefulWidget {
  final double size;
  final bool value;
  final Function(bool) onChanged;
  final Color activeColor;
  final Color notActiveColor;
  final bool disable;
  final String stateOne;
  final String stateTwo;
  final Color textColor;

  const BaseCustomSwitchButton({Key key, this.size = 18, @required this.value, @required this.onChanged, this.stateOne, this.stateTwo, this.activeColor, this.disable = false, this.textColor = Colors.white, this.notActiveColor = const Color(0xFFB6B6B6)}) : super(key: key);

  @override
  _BaseCustomMySwitchState createState() => _BaseCustomMySwitchState();
}

class _BaseCustomMySwitchState extends State<BaseCustomSwitchButton> {
  double get _switchSize => widget.size;

  Color get _activeColor => widget.activeColor ?? Color(0xFF36C65A);

  bool get showText => widget.stateOne != null && widget.stateTwo != null;

  bool isChecked;
  Duration _duration = Duration(milliseconds: 100);
  Curve _curves = Curves.easeInOut;

  @override
  void didUpdateWidget(covariant BaseCustomSwitchButton oldWidget) {
    if (widget.value != oldWidget.value) {
      isChecked = widget.value;
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void initState() {
    isChecked = widget.value;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(_switchSize / 2),
      child: GestureDetector(
        onTap: _onChange,
        child: AnimatedContainer(
          alignment: Alignment.center,
          curve: _curves,
          color: isChecked == true ? _activeColor : widget.notActiveColor,
          width: showText ? _switchSize * 2.5 : _switchSize * 2,
          height: _switchSize,
          padding: EdgeInsets.all(2),
          duration: _duration,
          child: _buildSwitchSizeBtn(),
        ),
      ),
    );
  }

  Widget _buildSwitchSizeBtn() {
    double _switchSizeBtn = _switchSize - 4;
    return Stack(
      children: [
        if (showText) AnimatedPositioned(left: isChecked != true ? _switchSize - 2 : 8, curve: _curves, duration: _duration, child: Text(isChecked ? widget.stateOne : widget.stateTwo, style: TextStyle(color: widget.textColor))),
        AnimatedPositioned(
          left: isChecked == true
              ? showText
              ? _switchSize * 1.5
              : _switchSize
              : 0,
          curve: _curves,
          duration: _duration,
          child: ClipOval(
            child: Container(height: _switchSizeBtn, width: _switchSizeBtn, color: Colors.white),
          ),
        )
      ],
    );
  }

  void _onChange() {
    if (widget.disable != true) {
      setState(() {
        isChecked = !isChecked;
        widget.onChanged(isChecked);
      });
    }
  }
}
